package com.jian.android.autojipai.app;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.graphics.Bitmap;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.IBinder;

import com.jian.android.autojipai.R;
import com.jian.android.autojipai.app.helper.FileTool;
import com.jian.android.autojipai.app.helper.LogTool;
import com.jian.android.autojipai.app.helper.TensorFlowLiteTool;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MediaProjectionService extends Service {
    private Intent data;
    private int dpi;
    private int height;
    private ImageReader imageReader;
    private Intent intent;
    private MediaProjectionManager mMediaProjectionManager;
    private MediaProjection mediaProjection;
    private int resultCode;
    private VirtualDisplay virtualDisplay;
    private int width;

    @Override // android.app.Service
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override // android.app.Service
    public void onCreate() {
        super.onCreate();
        LogTool.getInstance().printLog("TAG", "录屏服务onCreate");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        FileTool.getInstance().createFile(this, Build.VERSION.SDK_INT + ".txt");
        notification();
    }

    @Override // android.app.Service
    public int onStartCommand(Intent intent, int i, int i2) {
        this.intent = intent;
        this.data = (Intent) intent.getParcelableExtra("data");
        this.resultCode = this.intent.getIntExtra("code", -1);
        this.width = this.intent.getIntExtra("width", 1080);
        this.height = this.intent.getIntExtra("height", 1920);
        this.dpi = this.intent.getIntExtra("dpi", 1);
        return super.onStartCommand(intent, i, i2);
    }

    private void notification() {
        try {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder contentTitle = new Notification.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle("自动记牌");
            if (Build.VERSION.SDK_INT >= 26) {
                notificationManager.createNotificationChannel(new NotificationChannel("CHANNEL_ID_MEDIA_PROJECTION", "自动记牌", NotificationManager.IMPORTANCE_HIGH));
                contentTitle.setChannelId("CHANNEL_ID_MEDIA_PROJECTION");
            }
            Notification build = contentTitle.build();
            if (Build.VERSION.SDK_INT >= 29) {
                startForeground(1, build, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
            } else {
                startForeground(1, build);
            }
        } catch (Exception e) {
            e.printStackTrace();
            StringWriter stringWriter = new StringWriter();
            e.printStackTrace(new PrintWriter((Writer) stringWriter, true));
            FileTool.getInstance().saveException(this, stringWriter.toString(), "Service异常.txt");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String str) {
        startProjection(str);
    }

    private void startProjection(String str) {
        if (str.equals("getBitmap")) {
            LogTool.getInstance().printLog("TAG", "开始截取屏幕截图");
            if (this.intent == null) {
                LogTool.getInstance().printLog("TAG_1", "Intent为null");
                return;
            }
            LogTool.getInstance().printLog("TAG", "开始截取屏幕截图1");

            if (mMediaProjectionManager ==null){
                this.mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            }
            if (mediaProjection ==null){
                this.mediaProjection = this.mMediaProjectionManager.getMediaProjection(this.resultCode, this.data);
            }
            if (virtualDisplay!=null){
                try {
                    virtualDisplay.release();
                }catch (Exception e){

                }
            }
            if (imageReader !=null && imageReader.getSurface()!=null){
                try {
                    imageReader.close(); // 关闭旧的ImageReader
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            imageReader = ImageReader.newInstance(this.width, this.height, 1, 2);
            imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
                @Override
                public  void onImageAvailable(ImageReader imageReader) {
                    detectorImage(imageReader);
                }
            }, null);

            if (imageReader.getSurface() == null) {
                FileTool.getInstance().createFile(this, "SISNULL.txt");
            }

            virtualDisplay = this.mediaProjection.createVirtualDisplay("screen", this.width, this.height, this.dpi, 16, this.imageReader.getSurface(), null, null);


        }
    }


    Image acquireLatestImage=null;
    public void detectorImage(ImageReader imageReader) {
        LogTool.getInstance().printLog("TAG", "detectorImage");
        if (acquireLatestImage !=null){
            acquireLatestImage.close();
        }
        if (!App.isStartDetection){
            LogTool.getInstance().printLog("TAG", "stop");

        }else {
            LogTool.getInstance().printLog("TAG_1", "reader.acquireLatestImage()");
            acquireLatestImage = imageReader.acquireLatestImage();
            if (acquireLatestImage == null) {
                FileTool.getInstance().createFile(this, "IISNULL.txt");
                LogTool.getInstance().printLog("TAG", "获取屏幕Image为空");
            }else {
                try {
                    Bitmap image2Bitmap = image2Bitmap(acquireLatestImage);
                    if (image2Bitmap == null) {
                        FileTool.getInstance().createFile(this, "BISNULL.txt");
                    } else if (App.isStartDetection && App.isCanDetection) {
                        TensorFlowLiteTool tensorFlowLiteTool = TensorFlowLiteTool.getInstance();
                        tensorFlowLiteTool.initObjectDetector(getApplicationContext());
                        tensorFlowLiteTool.detector(image2Bitmap);
                    }
                } catch (Exception e) {
                    FileTool.getInstance().createFile(this, "TFLE.txt");
                    LogTool.getInstance().printLog("TAG_1", "检测异常：" + e.getMessage());
                }
            }


        }
    }

    private Bitmap image2Bitmap(Image image) {
        int width = image.getWidth();
        int height = image.getHeight();
        LogTool.getInstance().printLog("TAG", "Image宽度：" + width);
        LogTool.getInstance().printLog("TAG", "Image高度：" + height);
        Image.Plane[] planes = image.getPlanes();
        ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = ((planes[0].getRowStride() - (pixelStride * width)) / pixelStride) + width;
        Bitmap createBitmap = Bitmap.createBitmap(rowStride, height, Bitmap.Config.ARGB_8888);
        createBitmap.copyPixelsFromBuffer(buffer);
        float f = width*1.0f / height;
        int i = (int) (rowStride * f);
        int i2 = (height - i) / 2;
        LogTool.getInstance().printLog("TAG", "宽高比：" + f);
        LogTool.getInstance().printLog("TAG", "picHeight高度：" + i);
        LogTool.getInstance().printLog("TAG", "y：" + i2);
        if (i2 < 0) {
            FileTool.getInstance().createFile(this, "y_0.txt");
            image.close();
            return null;
        }
        Bitmap createBitmap2 = Bitmap.createBitmap(createBitmap, 0, i2, rowStride, i);
//        Bitmap createBitmap2 = Bitmap.createBitmap(createBitmap, 0, 0, width, height);

        if (createBitmap != null && !createBitmap.isRecycled()) {
            createBitmap.recycle();
        }
        image.close();
        return createBitmap2;
    }

    @Override // android.app.Service
    public void onDestroy() {
        try {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
        } catch (Exception e) {
          e.printStackTrace();
        }
        super.onDestroy();
    }
}
